﻿/// <summary>
/// u3d事件管理部分代码
/// 2015.04.18 - Jiangliwu
/// </summary>
/// 


using System.Collections;
using System.Collections.Generic;
using VFramework;

namespace VFramework{
	
	public class EventData
	{
		public string name;
		public object data;
		
		public EventData(string eventName , object data){
			this.name = eventName;
			this.data = data;
		}
	}


	/// <summary>
	/// 事件处理
	/// </summary>
	public class DelegateEvent {
		public delegate object EHandler (EventData eventData);
		public event EHandler ehandler = null;
		public object invoke( EventData data ) {
			if (ehandler != null ){
				return ehandler( data );
			}
			return null;
		}
		public void removeHandler( EHandler h ) {
			ehandler -= h;
		}
		
		public void addHandler( EHandler h){
			ehandler += h;
		}
		
	}

	/// <summary>
	/// 事件管理
	/// </summary>
	public class EventMgr : ISingleton{
		private	Dictionary<string,DelegateEvent> _eventTable = null;

		private EventMgr(){}

		public static EventMgr getInstance(){
			return Singleton<EventMgr>.getInstance ();
		}

		public void init(){
			_eventTable = new Dictionary<string,DelegateEvent> ();
		}

		public void release(){
			clearEvent ();
		}



		public void addEvent( string eventName, DelegateEvent.EHandler h){
			DelegateEvent de = null;
			if (_eventTable.ContainsKey (eventName)) {
				de = _eventTable [eventName];
			} else {
				de = new DelegateEvent();
				_eventTable[eventName] = de;
			}

			VLogger.debug (" ---add event ---- " + eventName);
			de.addHandler (h);
		}

		/// <summary>
		/// 删除事件，若handler为null，则删除type所有handler
		/// </summary>
		/// <param name="type">eventType</param>
		/// <param name="h">handler</param>
		public void removeEvent(string type,DelegateEvent.EHandler h){

			if (!_eventTable.ContainsKey (type)) {
				return;	
			}

			VLogger.debug (" --- removeEvent ---- " + type);
			if (h == null) {
				_eventTable[type] = null;
				return;
			}
			_eventTable[type].removeHandler (h);
		}

		/// <summary>
		/// Clears the event.
		/// </summary>
		public void clearEvent(){
			VLogger.debug (" ------------------ clear events -------------- ");
			_eventTable.Clear ();
		}

		/// <summary>
		/// 分发事件,注意:返回值为最后绑定的handler返回值,
		/// </summary>
		/// <returns>The event.</returns>
		/// <param name="type">Type.</param>
		/// <param name="data">Data.</param>
		public object dispatchEvent(string type , object data = null){
			if (!_eventTable.ContainsKey (type)) {
				VLogger.error(" ---- cannot find handler = " + type);
				return null;	
			}
			return _eventTable[type].invoke (new EventData (type, data));
		}
	}
}